package com.mechat.common.common.event.listener;

import com.mechat.common.common.event.UserRegisterEvent;
import com.mechat.common.user.dao.UserDao;
import com.mechat.common.user.domain.entity.User;
import com.mechat.common.user.domain.enums.IdempotentEnum;
import com.mechat.common.user.domain.enums.ItemEnum;
import com.mechat.common.user.service.IUserBackpackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class UserRegisterListener {
    @Autowired
    private IUserBackpackService iUserBackpackService;

    @Autowired
    private UserDao userDao;

    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendCard(UserRegisterEvent event) {
        // 送一张改名卡
        User user = event.getUser();
        iUserBackpackService.acquireItemCustomLock(user.getId(),
                ItemEnum.MODIFY_NAME_CARD.getId(),
                IdempotentEnum.UID,
                user.getId().toString());
    }

    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendBadge(UserRegisterEvent event) {
        // 前10名、100名的注册徽章
        User user = event.getUser();
        int registerCount = userDao.count();
        if (registerCount <= 10) {
            iUserBackpackService.acquireItemCustomLock(user.getId(),
                    ItemEnum.REG_TOP10_BADGE.getId(),
                    IdempotentEnum.UID,
                    user.getId().toString());
        } else if (registerCount <= 100) {
            iUserBackpackService.acquireItemCustomLock(user.getId(),
                    ItemEnum.REG_TOP100_BADGE.getId(),
                    IdempotentEnum.UID,
                    user.getId().toString());
        }
    }
}
